package com.zhangchuchu.neohealth.controller;

import com.zhangchuchu.neohealth.entity.ChatMessage;
import com.zhangchuchu.neohealth.entity.User;
import com.zhangchuchu.neohealth.entity.UserProfile;
import com.zhangchuchu.neohealth.service.ChatMessageService;
import com.zhangchuchu.neohealth.service.UserProfileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/chat")
@CrossOrigin(origins = "*") // 允许跨域请求
public class ChatMessageController {
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    private ChatMessageService chatMessageService;

    @Autowired
    private UserProfileService userProfileService;

    // 获取当前用户
    @GetMapping("/currentUser")
    public Map<String, Object> getCurrentUser(HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User)session.getAttribute("user");

        if (currentUser == null) {
            response.put("code", 401);
            response.put("message", "未登录");
        } else {
            response.put("code", 200);
            response.put("data", currentUser);
        }
        return response;
    }

    /**
     * 获取左侧好友列表（最近联系人的最新消息）
     * @param recipient 当前登录用户
     * @return 好友列表，每个好友的最后一条消息
     */
    @GetMapping("/friends")
    public Map<String, Object> getFriendsList(@RequestParam String recipient) {
        List<ChatMessage> friendList = chatMessageService.GetLastMessagesBySender(recipient);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "获取好友列表成功");
        response.put("data", friendList);
        return response;
    }

    /**
     * 获取聊天记录（与指定好友）
     * @param sender    当前用户
     * @param recipient 聊天对象
     * @return 双方的聊天记录（按时间升序排列）
     */
    @GetMapping("/history")
    public Map<String, Object> getChatHistory(@RequestParam String sender, @RequestParam String recipient) {
        List<ChatMessage> chatHistory = chatMessageService.getChatHistory(sender, recipient);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "获取聊天记录成功");
        response.put("data", chatHistory);
        return response;
    }
    /**
     * 获取个人信息
     * @param nickname    昵称
     * @return 个人信息
     */
    @GetMapping("/userProfile")
    public Map<String, Object> getUserProfile(@RequestParam String nickname) {
        UserProfile userProfile = userProfileService.findByNickname(nickname);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "获取个人信息");
        response.put("data", userProfile);
        return response;
    }
    /**
     * 存入聊天框内容
     * @param message    消息主体
     * @return null
     */
    @MessageMapping("/privateMessage")
    public void handlePrivateMessage(ChatMessage message) {
        // 补全默认值（id 不传，isRead 和 isDeleted 默认为 false）
        message.setIsRead(false);
        message.setIsDeleted(false);
        message.setTimestamp(LocalDateTime.now());

        // 保存到数据库
        chatMessageService.saveMessage(message);

        // 推送给接收者
        messagingTemplate.convertAndSendToUser(
                message.getRecipient(), "/queue", message);


        // 也推送给发送者，让他看到真实消息（含数据库id、时间等）
        messagingTemplate.convertAndSendToUser(
                message.getSender(), "/queue", message);
        System.out.println("Message sent to " + message.getRecipient());
    }

    /**
     * 已读
     * @param sender 发送人
     * @param recipient 接收人
     */
    @GetMapping("/markAsRead")
    public Map<String, Object> markMessagesAsRead(@RequestParam String sender,@RequestParam String recipient) {
        chatMessageService.markMessagesAsRead(sender,recipient);
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "消息已读");
        return response;
    }
}
